package cn.zebra.dev.admin.module.admin.service.impl;

import cn.zebra.dev.admin.module.admin.dao.AdminRoleItemDao;
import cn.zebra.dev.admin.module.admin.entity.AdminRoleItemEntity;
import cn.zebra.dev.admin.module.admin.service.AdminRoleItemService;
import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.ibatis.plus.utils.Query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * 后台角色关联(多对多)
 *
 * @author runnable
 * @date 2019-09-07 17:03:30
 */
@Service
public class AdminRoleItemServiceImpl extends ServiceImpl<AdminRoleItemDao, AdminRoleItemEntity> implements AdminRoleItemService {

    @Override
    public PageUtils findPage(Map<String, Object> params) {
        IPage<AdminRoleItemEntity> page = this.page(
                new Query<AdminRoleItemEntity>(params).getPage(),
                new QueryWrapper<>()
        );

        return new PageUtils<>(page);
    }

    @Override
    public Long findRoleIdByAdminId(Long adminId) {
        QueryWrapper<AdminRoleItemEntity> wrapper = new QueryWrapper<>();
        wrapper.select("role_id");
        wrapper.apply("admin_id = {0}", adminId);
        return getOne(wrapper).getRoleId();
    }

    @SneakyThrows
    @Override
    public boolean saveBatch(Collection<AdminRoleItemEntity> entityList) {
        if (entityList != null && entityList.size() > 0) {
            List<Future<Boolean>> list = new ArrayList<>(entityList.size());
            entityList.forEach(entity -> list.add(this.asyncSave(entity)));
            for (int i = list.size() - 1; i >= 0; i--) {
                if (!list.get(i).get()) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    @Override
    @Async
    public Future<Boolean> asyncSave(AdminRoleItemEntity entity) {
        return AsyncResult.forValue(this.save(entity));
    }

    /**
     * 根据 admin_id 字段 查找role_id 集合
     *
     * @param adminId 后台用户id
     * @return 角色id集合
     */
    @Override
    public List<Long> findRoleIdListByAdminId(Long adminId) {
        LambdaQueryWrapper<AdminRoleItemEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminRoleItemEntity::getAdminId, adminId);
        return this.list(wrapper).stream().map(AdminRoleItemEntity::getRoleId).collect(Collectors.toList());
    }
}
